package com.qipay.sp.excutor.gaoxin;

import com.alibaba.fastjson.JSONObject;
import com.qipay.baas.model.Order;
import com.qipay.order.config.OrderStateEnum;
import com.qipay.order.service.OrderService;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.sp.excutor.AbstractExcutor;
import com.qipay.utils.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Component
public class GaoxinNativeExcutor extends AbstractExcutor {

    private final static String API_URL = "api_url";
    @Autowired
    OrderService orderService;
    @Override
    protected Map<String, Object> getApiParams(Order order, Map<String, Object> spconfig, Map<String, Object> extendOrderParams) {
        Map<String, Object> apiParams = new HashMap<>();
        apiParams.put("tradeNo", order.getTradeNo());
        apiParams.put("orderPrice", new BigDecimal(order.getAmount()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN).toString());
        apiParams.put("productName", order.getBody());
        apiParams.put("remark", order.getCpId());
        return apiParams;
    }

    @Override
    protected Map<String, Object> run(Map<String, Object> spconfig, Map<String, Object> params) throws Exception {
        Object apiUrl = getVal(spconfig, API_URL);
        Object merchantId = getVal(spconfig, "merchantId");
        Object notifyUrl = getVal(spconfig, "notify_url");
        Object returnUrl = getVal(spconfig, "return_url");
        Object key = getVal(spconfig, "key");

        params.put("merchantId", merchantId);
        params.put("notifyUrl", notifyUrl);
        params.put("returnUrl", returnUrl);

        String sign = MD5Util.getSign(params, key.toString()).toUpperCase();
        params.put("sign", sign);
        params.put("respType", "json");

        String result = http(apiUrl.toString(),params);
        if (StringUtils.isBlank(result)) {
            throw new Exception(this.getClass()+"请求支付接口失败："+result);
        }

        Order order = orderService.getByTradeNo(params.get("tradeNo").toString());
        Map<String, Object> resultMap = new HashMap<>();
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getIntValue("code") == 200) {
            JSONObject obj = jsonObject.getJSONObject("obj");
            resultMap.put("status", ApiStatusEnum.OK.getCode());
            resultMap.put("pay_info", obj.getString("url"));
            order.setState(OrderStateEnum.WAITING.getType());
        } else {
            resultMap.put("status", "1");
            resultMap.put("message", result);
            order.setState(OrderStateEnum.REQERROR.getType());
        }
        orderService.update(order);
        return resultMap;
    }

}
